<template>
  <div class="category">
   <div class="left">
    <van-sidebar v-model="active" @change="handleCategoryChange">
  <van-sidebar-item 
  v-for="category in categories"
  :key="category"
  :title="category.trim()" 
  />
  <!-- <van-sidebar-item title="标签名称" />
  <van-sidebar-item title="标签名称" /> -->
</van-sidebar>
   </div>
   <!-- 右侧渲染分类下的品牌数据 -->
   <div class="right">
    <van-grid :border="false" :column-num="3">
  <van-grid-item 
  v-for="(item,index) in brands"
  :key="index"
  icon="photo-o"
  :text="item.brand" />

</van-grid>
   </div>

    
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { getAllCategories , getBrandsBycategory} from "@/api/category"


//激活分类的索引
const active = ref(0);


//查询渲染所有分类
const categories = ref<string[]>([])
const fecthAllCategories = async() =>{
  try{
    const result = await getAllCategories()
    console.log("所有分类",result)
    categories.value = result
    
    //初始查询完所有分类，先默认查询第一个分类下的所有品牌并渲染
    handleCategoryChange(0)
  }catch (error){
    console.error("异常",error)
  }
}
fecthAllCategories()

//主分类切换从，查询分类下品牌数据 
type Brand = {
  brand:string  
}

const brands = ref<Brand[]>([])
const  handleCategoryChange = async(index:number) =>{
  console.log("change:",index)
  //更具切换时的索引，获取分类数组中对应的分类字符串
  const category = categories.value[index]
  try{
    //根据匪类查询品牌
    const result :any = await getBrandsBycategory(category)
    console.log("品牌：",result)
    brands.value = result
  }catch(error){ 
    console.error("异常：",error)
  }
}
</script>

<style lang="less" scoped>
.category{
  display: flex;

  .right{
    flex: 1;

  }
}

</style >
 